package com.test.realcityalfa.frmwrk;

import com.test.realcityalfa.Constants;
import com.test.realcityalfa.R;
import com.test.realcityalfa.beans.AdCountResponseBean;
import com.test.realcityalfa.connection.InternetConnection;
import com.test.realcityalfa.connection.RequestMethodFactory;
import com.test.realcityalfa.json.requests.JsonRequestFactory;
import com.test.realcityalfa.json.requests.RequestBuilder;
import com.test.realcityalfa.json.responses.AdCountResponseBuilder;
import com.test.realcityalfa.json.responses.ResponseFactory;

import android.app.Activity;
import android.util.Log;
import android.widget.TextView;

public class LoadAdCountAsyncTask extends CustomAsyncTask{
	InternetConnection internetConnection;
	RequestBuilder jsonBuilder;
	Activity activity;
	TextView outputView;
	
	public LoadAdCountAsyncTask(Activity activity, RequestBuilder builder) 
	{
		super(activity.getApplicationContext());
		this.jsonBuilder = builder;
		this.activity = activity;
		internetConnection = new InternetConnection(RequestMethodFactory.GET_METHOD);
	}

	@Override
	protected Object asyncOperation() throws Throwable 
	{
		JsonRequestFactory requestFactory = new JsonRequestFactory(this.jsonBuilder);
		
		this.internetConnection.setRequestData(this.jsonBuilder.createRequest(null));
		if(this.internetConnection.isConnectionAvailable(this.activity))
		{
			String tmp = this.internetConnection.execute();
			Log.d(getClass().getName(), "Received data: " + tmp);
			
			ResponseFactory responseResolver = new ResponseFactory(new AdCountResponseBuilder());
			
			
			publishProgress(responseResolver.getResponseBean(tmp));
		}
		return null;
	}

	@Override
	protected void onResult(Object result) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onProgress(Object update) throws Exception 
	{
		
		Object[] object = (Object[])update;
		if(object[0] != null && this.outputView != null)
		{
			TextView adCountLine = outputView;
			AdCountResponseBean data = ((AdCountResponseBean) object[0]);
			adCountLine.setText(String.format(activity.getString(R.string.dashboardAdCount), data.getTotalCount()));
		}
				
	}
	
	public void setOutpuTextView(TextView view)
	{
		this.outputView = view;
	}

}
